<template>
  <div>
    <!--  面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图区域  -->
    <el-card class="box-card">
      <!--  搜索框和按钮区域  -->
      <el-row :gutter="20">
        <!--  搜索  -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <!--  添加用户  -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--  用户列表数据区域  -->
      <el-table :data="userList" stripe border>
        <!--为表格添加索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="usersStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <!-- 接收这一行的数据  -->
          <template slot-scope="scope">
            <!--  修改  -->
            <el-button @click="alterUser(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <!--  删除  -->
            <el-button @click="deleteUser(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
            <!--  分配角色  -->
            <el-tooltip class="item" effect="dark" content="分配角色" :enterable="false" placement="top">
              <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--  分页区域  -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 8]" :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框  -->
    <el-dialog @close="addDialogClose" title="添加用户" :visible.sync="dialogVisible" width="30%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" type="text"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
    </el-dialog>
    <!--  修改用户的对话框  -->
    <el-dialog @close="alterDialogClose" title="修改用户信息" :visible.sync="alterDialogVisible" width="30%">
      <el-form :model="alterForm" :rules="addFormRules" ref="alterFormRef" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="alterForm.username" disabled type="text"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="alterForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="alterForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="alterDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="alterSubmit">确 定</el-button>
          </span>
    </el-dialog>
    <!--  分配角色的对话框  -->
    <el-dialog  title="分配角色" :visible.sync="setDialogVisible" width="30%">
      <p>当前的用户：{{userData.username}}</p>
      <p>当前的角色：{{userData.role_name}}</p>
      <p>分配新角色：
        <el-select v-model="selectRolesId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
            <el-button @click="setDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setSubmit">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Users",
    data() {
      /*  自定义校验邮箱规则*/
      let checkEmial = (rule, value, cb) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          cb();
        } else {
          cb(new Error('请输入合法邮箱'));
        }
      }
      /*  自定义校验手机号规则*/
      let checkMobile = (rule, value, cb) => {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          cb();
        } else {
          cb(new Error('请输入合法手机号'));
        }
      }
      return {
        selectRolesId:'',
        rolesList: [],
        userData: {},
        setDialogVisible: false,
        alterDialogVisible: false,
        alterForm: {
          username: '',
          email: '',
          mobile: ''
        },
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        addFormRules: {
          username: [
            {required: true, message: '请输入用户名称', trigger: 'blur'},
            {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmial, trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'}
          ]
        },
        dialogVisible: false,
        /*  对象存储获取的用户列表参数  */
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 8
        },
        userList: [],
        total: 0
      }
    },

    created() {
      /*  将用户列表信息获取函数挂载到生命周期函数上*/
      this.getUsersList();
    },

    methods: {
      /*  确定分配角色  */
      async setSubmit(){
        console.log(this.selectRolesId);
        if (!this.selectRolesId){
          this.$message.error('请选择要分配的角色');
        }else {
          const  {data:subRes} = await this.$http.put(`users/${this.userData.id}/role`,
            {rid:this.selectRolesId}
            );
          if (subRes.meta.status === 200){
            this.getUsersList();
            this.setDialogVisible = false;
          }else {
            this.$message.error('分配角色失败')
          }
        }
      },
      /*  分配角色*/
      async setRole(userData) {
        this.userData = userData;
        const {data: setRes} = await this.$http.get('roles');
        if (setRes.meta.status === 200) {
          this.rolesList = setRes.data;
          this.setDialogVisible = true;
        } else {
          this.$message.error('角色信息获取失败');
        }
      },
      /*  删除用户  */
      deleteUser(deleteId) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          /*  确定删除该用户 */
          const {data: deleteRes} = await this.$http.delete("users/" + deleteId);
          if (deleteRes.meta.status === 200) {
            this.$message.success("成功删除用户");
            this.getUsersList();
          } else {
            this.$message.error("删除用户失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      /*  确定修改用户信息 */
      alterSubmit() {
        this.$refs.alterFormRef.validate(async (valid) => {
          if (!valid) {
            return;
          } else {
            const {data: alterRes} = await this.$http.put('users/' + this.alterForm.id, {
              email: this.alterForm.email,
              mobile: this.alterForm.mobile
            });
            if (alterRes.meta.status === 200) {
              this.alterDialogVisible = false;
              this.$message.success('提交成功');
              this.getUsersList();
            } else {
              this.$message.error('提交失败');
            }
          }
        })
      },
      /*  修改用户对话框重置*/
      alterDialogClose() {
        this.$refs.alterFormRef.resetFields();
      },
      /*  获取修改用户信息*/
      async alterUser(alterScopeId) {
        this.alterDialogVisible = true;
        const {data: alterRes} = await this.$http.get('users/' + alterScopeId);
        if (alterRes.meta.status === 200) {
          this.alterForm = alterRes.data;
        } else {
          this.alterDialogVisible = false;
          return this.$message.error('获取用户信息失败');
        }
      },
      /*  确定添加新用户 */
      addUser() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) {
            console.log('error submit!!');
            return;
          } else {
            const {data: addRes} = await this.$http.post('users', this.addForm);
            if (addRes.meta.status === 201) {
              this.$message.success('提交成功');
              this.dialogVisible = false;
              this.getUsersList();
            } else {
              this.$message.error('提交失败');
            }
          }
        })
      },
      /*  监听添加用户对话框的关闭事件  */
      addDialogClose() {
        this.$refs.addFormRef.resetFields();
      },
      /*  switch 状态发生变化时的回调函数 */
      async usersStateChange(scopeRow) {
        /*  修改请求  */
        const {data: stateRes} = await this.$http.put(`users/${scopeRow.id}/state/${scopeRow.mg_state}`);
        if (stateRes.meta.status !== 200) {
          this.$message.error("更新用户状态失败");
          /*  更新失败时阻止界面状态修改   */
          scopeRow.mg_state = !scopeRow.mg_state;
        } else {
          this.$message.success("用户状态更新成功");
        }
      },
      /*  监听页码的事件(页码值切换时触发的函数)   */
      handleCurrentChange(nowCurrent) {
        this.queryInfo.pagenum = nowCurrent;
        this.getUsersList();
      },
      /*  监听 pageSize 改变的事件(切换每页显示多少条信息的菜单时触发) */
      handleSizeChange(newPageSize) {
        this.queryInfo.pagesize = newPageSize;
        this.getUsersList();
      },
      /*  获取用户列表信息  */
      async getUsersList() {
        const {data: res} = await this.$http.get("users", {params: this.queryInfo});
        // console.log(res);
        if (res.meta.status === 200) {
          this.userList = res.data.users;
          this.total = res.data.total;
        } else {
          this.$message.error('用户列表获取失败');
        }
      }
    }
  }
</script>

<style scoped>

</style>
